package com.assisjrs.jpaandroid.persistence;

import java.text.MessageFormat;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import android.content.Context;

public class Persistence {
	public static String PERSISTENCE_PROVIDER = "com.assisjrs.jpaandroid.persistence.PersistenceProvider";
	protected static final Set<PersistenceProvider> providers = new HashSet<PersistenceProvider>();

	public static EntityManagerFactory createEntityManagerFactory(final Context context, final String persistenceUnitName) {
		return createEntityManagerFactory(context, persistenceUnitName, null);
	}

	@SuppressWarnings("unchecked")
	public static EntityManagerFactory createEntityManagerFactory(final Context context, final String persistenceUnitName,
																  final Map<String, String> properties) {
		if(context == null) throw new IllegalArgumentException("O Parametro Persistence.createEntityManagerFactory.context deve ser diferente de null.");

		EntityManagerFactory emf = null;

		try {
			final Class<PersistenceProvider> persistenceProviderClass = (Class<PersistenceProvider>) Class
			        .forName(MessageFormat.format("{0}Impl", PERSISTENCE_PROVIDER));

			final PersistenceProvider persistenceProvider = persistenceProviderClass.newInstance();

			emf = persistenceProvider.createEntityManagerFactory(persistenceUnitName, properties);
		} catch (final ClassNotFoundException e) {
			throw new PersistenceException("No Persistence provider for EntityManager named " + persistenceUnitName);
		} catch (final InstantiationException e) {
			throw new PersistenceException("Erro ao inicializar o persistence provider.");
		} catch (final IllegalAccessException e) {
			throw new PersistenceException("Erro ao inicializar o persistence provider.");
		}

		if (emf == null) {
			throw new PersistenceException("No Persistence provider for EntityManager named " + persistenceUnitName);
		}

		return emf;
	}
}
